<template>
  <div class="statistics-cards">
    <el-card class="stats-card">
      <template #header>
        <div class="card-header">
          <h3>📈 详细统计</h3>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="4" animated />
      </div>

      <div v-else-if="statistics" class="stats-content">
        <div class="stats-grid">
          <el-tooltip
            effect="dark"
            :content="tooltipContents.totalFiles"
            placement="top"
            :show-after="300"
          >
            <div class="stat-card">
              <div class="stat-icon">📄</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.totalFiles }}</div>
                <div class="stat-label">总文件数</div>
              </div>
            </div>
          </el-tooltip>

          <el-tooltip
            effect="dark"
            :content="tooltipContents.totalDependencies"
            placement="top"
            :show-after="300"
          >
            <div class="stat-card">
              <div class="stat-icon">🔗</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.totalDependencies }}</div>
                <div class="stat-label">总依赖数</div>
              </div>
            </div>
          </el-tooltip>

          <el-tooltip
            effect="dark"
            :content="tooltipContents.packageDependencies"
            placement="top"
            :show-after="300"
          >
            <div class="stat-card">
              <div class="stat-icon">📦</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.packageDependencies }}</div>
                <div class="stat-label">包间依赖</div>
              </div>
            </div>
          </el-tooltip>

          <el-tooltip
            effect="dark"
            :content="tooltipContents.rootFileReferences"
            placement="top"
            :show-after="300"
          >
            <div class="stat-card">
              <div class="stat-icon">🏠</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.rootFileReferences }}</div>
                <div class="stat-label">根文件引用</div>
              </div>
            </div>
          </el-tooltip>

          <el-tooltip
            effect="dark"
            :content="tooltipContents.circularDependencies"
            placement="top"
            :show-after="300"
          >
            <div class="stat-card" :class="{ warning: statistics.circularDependencies > 0 }">
              <div class="stat-icon">⚠️</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.circularDependencies }}</div>
                <div class="stat-label">循环依赖</div>
              </div>
            </div>
          </el-tooltip>

          <el-tooltip
            effect="dark"
            :content="tooltipContents.maxDepth"
            placement="top"
            :show-after="300"
          >
            <div class="stat-card">
              <div class="stat-icon">🌊</div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.maxDepth }}</div>
                <div class="stat-label">最大深度</div>
              </div>
            </div>
          </el-tooltip>
        </div>

        <!-- 健康度评估 -->
        <div class="health-assessment">
          <h4>📊 项目健康度评估</h4>
          <div class="health-items">
            <el-tooltip
              effect="dark"
              content="基于循环依赖和依赖深度评估代码结构质量。良好的结构应该避免循环依赖，控制依赖深度在合理范围内。"
              placement="top"
              :show-after="300"
            >
              <div class="health-item">
                <span class="health-label">代码结构:</span>
                <el-tag :type="getStructureHealthType()" size="small">
                  {{ getStructureHealthText() }}
                </el-tag>
              </div>
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="基于平均依赖数和根文件引用比例评估依赖管理质量。良好的依赖管理应该控制文件间的耦合度。"
              placement="top"
              :show-after="300"
            >
              <div class="health-item">
                <span class="health-label">依赖管理:</span>
                <el-tag :type="getDependencyHealthType()" size="small">
                  {{ getDependencyHealthText() }}
                </el-tag>
              </div>
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="综合评估项目的整体健康度，满分 100 分。评分越高说明项目结构越合理，维护性越好。"
              placement="top"
              :show-after="300"
            >
              <div class="health-item">
                <span class="health-label">整体评分:</span>
                <el-tag :type="getOverallHealthType()" size="small">
                  {{ getOverallHealthScore() }}/100
                </el-tag>
              </div>
            </el-tooltip>
          </div>
        </div>
      </div>

      <div v-else class="error-container">
        <el-alert
          title="加载失败"
          description="无法加载统计数据"
          type="error"
          show-icon
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, type Ref } from 'vue';
import { AnalysisDataService } from '../services/analysis-data';

/**
 * 统计数据接口
 */
interface IStatistics {
  totalFiles: number;
  totalDependencies: number;
  packageDependencies: number;
  rootFileReferences: number;
  circularDependencies: number;
  maxDepth: number;
}

// 响应式数据
const loading: Ref<boolean> = ref(true);
const statistics: Ref<IStatistics | null> = ref(null);
const analysisService = AnalysisDataService.getInstance();

/**
 * 悬浮提示内容定义
 */
const tooltipContents = {
  totalFiles: '项目中所有被分析的文件总数，包括 .vue、.ts、.tsx 等源代码文件。这个数量反映了项目的整体规模。',
  totalDependencies: '项目中所有文件的依赖关系总数，包括本地文件依赖、第三方包依赖、工作空间包依赖等。数量越大表示项目复杂度越高。',
  packageDependencies: '工作空间内各包之间的依赖关系数量。在 Monorepo 项目中，这个指标反映了包之间的耦合程度。',
  rootFileReferences: '包文件对项目根目录文件的引用次数。这种引用可能违反项目的层级结构设计，数量过多需要重构。',
  circularDependencies: '项目中存在的循环依赖数量。循环依赖会导致代码结构混乱，应该尽量避免。理想情况下应该为 0。',
  maxDepth: '依赖关系的最大层级深度。深度过大（>8）可能表示项目结构过于复杂，需要考虑重构以降低复杂度。'
};

/**
 * 获取代码结构健康度类型
 */
const getStructureHealthType = (): string => {
  if (!statistics.value) return 'info';

  const { circularDependencies, maxDepth } = statistics.value;

  if (circularDependencies > 0) return 'danger';
  if (maxDepth > 8) return 'warning';
  return 'success';
};

/**
 * 获取代码结构健康度文本
 */
const getStructureHealthText = (): string => {
  if (!statistics.value) return '未知';

  const { circularDependencies, maxDepth } = statistics.value;

  if (circularDependencies > 0) return '存在循环依赖';
  if (maxDepth > 8) return '依赖层级较深';
  return '结构良好';
};

/**
 * 获取依赖管理健康度类型
 */
const getDependencyHealthType = (): string => {
  if (!statistics.value) return 'info';

  const { totalFiles, totalDependencies, rootFileReferences } = statistics.value;
  const avgDepsPerFile = totalFiles > 0 ? totalDependencies / totalFiles : 0;

  if (rootFileReferences > totalFiles * 0.3) return 'danger';
  if (avgDepsPerFile > 10) return 'warning';
  return 'success';
};

/**
 * 获取依赖管理健康度文本
 */
const getDependencyHealthText = (): string => {
  if (!statistics.value) return '未知';

  const { totalFiles, totalDependencies, rootFileReferences } = statistics.value;
  const avgDepsPerFile = totalFiles > 0 ? totalDependencies / totalFiles : 0;

  if (rootFileReferences > totalFiles * 0.3) return '根文件引用过多';
  if (avgDepsPerFile > 10) return '平均依赖较多';
  return '依赖管理良好';
};

/**
 * 获取整体健康度类型
 */
const getOverallHealthType = (): string => {
  const score = getOverallHealthScore();
  if (typeof score === 'string') return 'info';

  if (score >= 80) return 'success';
  if (score >= 60) return 'warning';
  return 'danger';
};

/**
 * 计算整体健康度评分
 */
const getOverallHealthScore = (): number | string => {
  if (!statistics.value) return '未知';

  const { circularDependencies, maxDepth, totalFiles, totalDependencies, rootFileReferences } = statistics.value;

  let score = 100;

  // 循环依赖扣分
  if (circularDependencies > 0) {
    score -= Math.min(30, circularDependencies * 10);
  }

  // 依赖深度扣分
  if (maxDepth > 5) {
    score -= Math.min(20, (maxDepth - 5) * 5);
  }

  // 根文件引用扣分
  if (totalFiles > 0) {
    const rootRefRate = rootFileReferences / totalFiles;
    if (rootRefRate > 0.2) {
      score -= Math.min(25, rootRefRate * 50);
    }
  }

  // 平均依赖数扣分
  if (totalFiles > 0) {
    const avgDeps = totalDependencies / totalFiles;
    if (avgDeps > 8) {
      score -= Math.min(15, (avgDeps - 8) * 2);
    }
  }

  return Math.max(0, Math.round(score));
};

/**
 * 加载统计数据
 */
const loadStatistics = async (): Promise<void> => {
  try {
    loading.value = true;

    // 检查是否已有数据
    let currentData = analysisService.getCurrentAnalysisData();

    if (!currentData) {
      // 加载数据（路径从环境变量获取）
      await analysisService.loadAnalysisData();
      currentData = analysisService.getCurrentAnalysisData();
    }

    if (currentData) {
      statistics.value = currentData.statistics;
    }
  } catch (error) {
    console.error('加载统计数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadStatistics();
});
</script>

<style scoped>
.statistics-cards {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.loading-container {
  padding: 20px;
}

.stats-content {
  padding: 10px 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  gap: 12px;
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
  border-left: 4px solid #409eff;
  cursor: help;
}

.stat-card:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card.warning {
  border-left-color: #f56c6c;
  background: #fef0f0;
}

.stat-card.warning:hover {
  background: #fde2e2;
}

.stat-icon {
  font-size: 24px;
  margin-right: 12px;
  min-width: 32px;
  text-align: center;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.health-assessment {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.health-assessment h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.health-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.health-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  cursor: help;
  border-radius: 4px;
  padding: 8px 12px;
  transition: background-color 0.2s ease;
}

.health-item:hover {
  background-color: #f5f7fa;
}

.health-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.error-container {
  padding: 20px;
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  }

  .stat-value {
    font-size: 20px;
  }

  .health-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>
